<?php
namespace Admin\Service;

/**
 * 字段管理
 *
 * @package         YDCMS
 * @author          QQ:644157559 <644157559@qq.com>
 * @version         $Id: FieldService.class.php v1.0 2014-06-13 17:27:03 $
 */
class FieldService extends CommonService {

    /**
     * 检查字段是否可用
     * @param  array $field Field数组
     * @param    int    $id 需要更新field的id
     * @return mixed
     */
    public function checkField($field, $id) {
        // 字段类型约束验证
        $result = $this->checkType($field['type']);
        if (!$result['status']) {
            return $result;
        }

        if (!D('Model', 'Service')->existModel($field['model_id'])) {
            return $this->errorResultReturn('字段对应的模型不存在！');
        }

        $Field = $this->getD();
        if ($Field->isValid($field, $id)) {
            return $this->resultReturn(true);
        }

        return $this->errorResultReturn($Field->getError());
    }
    
    /**
     * 检查字段type
     * @param  array $field
     * @return array
     */
    public function checkType($type) {
        if(isset($this->getD()->fieldtype[$type])){
            return $this->resultReturn(true);
        }else{
            return $this->errorResultReturn("非法字段类型！");
        }
    }
    /**
     * 添加字段
     * @param  array Field数组
     * @return array
     */
    public function add($field) {
        $model = M('Model')->getById($field['model_id']);
        $m = M($model['addtable']);
        $data['model_id'] = intval($field['model_id']);
        $data['name'] = trim($field['name']);
        $data['comment'] = trim($field['comment']);
        $data['type'] = trim($field['type']);
        $data['value'] = trim($field['value']);
        $data['length'] = intval($field['length']) > 250 ? 250 : (intval($field['length']) < 0 ? 50 : intval($field['length']));
        $fieldModel = $this->getD();
        $field_info = $fieldModel->where(array("model_id" => $data['model_id'], "name" => $data['name']))->select();
        
        $mainTableFields = M("Content")->getDbFields();
        $addTableFields = M($model['addtable'])->getDbFields();
        
        $farr = array_merge($mainTableFields, $addTableFields);
        
        $f = '';
        foreach($farr as $v)
        {
            $f .= ($f=='' ? $v : ' '.$v);
        }
        if(in_array($data['name'], $farr) || isArrayAndNotEmpty($field_info)){
            return $this->errorResultReturn("字段名称不合法，如下字段名已经存在，建议在名称后加上数字以区分：\n" . $f);
        }
        if(false === ($field_data = $fieldModel->create($data))){
            return $this->errorResultReturn($fieldModel->getError());
        }
        $field_id = $fieldModel->add($field_data);
        if($field_id){
            switch ($data['type']) {
                case "text":
                case "img":
                case "imgfile":
                    $field_type = "VARCHAR ( {$data['length']} )";
                    break;
                case "select":
                case "radio":
                case "checkbox":
                    $vdefault = "";
                    $field_type = "VARCHAR ( {$data['length']} )";
                    break;
                case "textchar":
                    $field_type = "CHAR( {$data['length']} )";
                    break;
                case "multitext":
                    $field_type = 'TEXT';
                     $vdefault = "";
                    break;
                case "htmltext":
                    $field_type = 'MEDIUMTEXT';
                    $vdefault = "";
                    break;
                case "int":
                    $field_type = "INT( 10 )";
                    $vdefault = intval($data['value']);
                    break;
                case "float":
                    $field_type = "FLOAT( 10,2 )";
                    $vdefault = floatval($data['value']);
                    break;
                default:
                    $field_type = 'VARCHAR( 250 )';
                    $vdefault = "";
                    break;
            }
            $sql = "ALTER TABLE __TABLE__ ADD `{$data['name']}` {$field_type} CHARACTER SET utf8 NOT NULL DEFAULT '{$vdefault}' COMMENT '{$data['comment']}'";
            
            if(false === $m->execute($sql)){
                $fieldModel->delete($field_id);
                return $this->errorResultReturn("添加字段失败");
            }else{
                return $this->resultReturn(true);
            }
        }else{
            return $this->errorResultReturn("添加字段失败");
        }
    }

    /**
     * 更新字段
     * @param  array $field
     * @return array
     */
    public function update($field) {
        if (!$this->existField($field['id'])) {
            return $this->resultReturn(false);
        }

        $Field = $this->getD();
        $old = $Field->getById($field['id']);

        // 得到数据表名称
        $model = M('Model')->field('addtable')->getById($field['model_id']);

        // 更新field
        if(false === ($field = $Field->create($field))){
        
            
        }
        $status = $Field->save($field);
        // name
        if ($field['name'] != $old['name']
            || $field['type'] != $old['type']
            || $field['length'] != $old['length']) {
            $Field->alterColumnAttr($model['addtable'],
                                            $old['name'],
                                            $field['name'],
                                            $field['type'],
                                            $field['length'],
                                            $field['comment']);
            }
        if (false === $status) {
            $Field->alterColumnAttr($model['addtable'],
                                    $field['name'],
                                    $old['name'],
                                    $old['type'],
                                    $old['length'],
                                    $old['comment']);

            return $this->resultReturn(false);
        }

        return $this->resultReturn(true);
    }

    /**
     * 删除字段
     * @param  int   $id 需要删除字段的id
     * @return array
     */
    public function delete($id) {
        if (!isset($id) || !$this->existField($id)) {
            return resultReturn(false);
        }

        $Field = $this->getD();
        $old = $Field->getById($id);
        if(!isArrayAndNotEmpty($old)){
            return $this->errorResultReturn("您要删除的字段不存在！");
        }
        $model = M('Model')->field('addtable')->getById($old['model_id']);
        
        // 删除表中的字段
        $dcs = $Field->dropColumn(C('DB_PREFIX').$model['addtable'], $old['name']);

        if (false === $dcs) {
            return $this->resultReturn(false);
        }
        $Field->where("id={$old['id']}")->delete();
        
        return $this->resultReturn(true);
    }
    

    /**
     * 检查字段是否存在
     * @param  int     $fieldId
     * @return boolean
     */
    public function existField($fieldId) {
        if ($this->getM()->where("id = {$fieldId}")->count() > 0) {
            return true;
        }

        return false;
    }

    /**
     * 按modelId得到所有字段
     * @param type $modelId
     * @param type $field
     * @param type $autofield
     * @return type
     */
    public function getByModelId($modelId, $field = "*", $autofield = false) {
        $where = array("model_id" => $modelId);
        if($autofield !== false){
            $where['autofield'] = $autofield;
        }
        return $this->getM()
                    ->field($field)
                    ->where($where)
                    ->select();
    }

    protected function getModelName() {
        return 'Field';
    }
}
